package cn._2dland.servlet;

import java.io.IOException;
import java.math.BigInteger;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import cn._2dland.tools.DamnServlet;
import cn._2dland.utils.HttpUtils;

public class QQServlet extends HttpServlet {
	private static final long serialVersionUID = 7156248084112257076L;
	private static final String QQ_URL = "http://vv.video.qq.com/geturl?otype=xml&platform=1&vid=";
	private static final String QQ_VIDEO_URL = "http://vtop.qqvideo.tc.qq.com/";

	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String referrer = req.getHeader("Referer");

		String duration = null;
		String videoUrl = null;
		try {
			String vid = req.getParameter("vid");
			if(vid == null || "".equals(vid))
				throw new Exception("无效vid！");

			if(referrer == null) {
				String ran = req.getParameter("ran");
				if(ran == null)
					ran = String.valueOf(new Random().nextFloat());

				// 读取XML
				String url = QQ_URL + vid + "&ran=" + ran;
				Document doc = HttpUtils.getHTTPXMLDocument(url);
				Element root = doc.getDocumentElement();

				Element dur = (Element)root.getElementsByTagName("dur").item(0);
				duration = dur!=null ? dur.getFirstChild().getNodeValue() : "9999";
				videoUrl = getVideoURL(vid);
			} else {
				videoUrl = new StringBuffer(DamnServlet.DAMN_API_URL).append("?src=qq&vid=").append(vid).toString();
				duration = "0";
			}
		}
		catch (Exception e) {
			e.printStackTrace();
			videoUrl = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + req.getContextPath() + "/parse_failed.flv";
			duration = "5022";
		}

		// 生成XML，并返回给客户端
		StringBuffer infoXML = new StringBuffer();
		infoXML.append("<?xml version=\"1.0\" encoding=\"UTF-8\"  standalone=\"no\" ?>");
		infoXML.append("<root><vd><vi>");
		infoXML.append("<dur>").append(duration).append("</dur>");
		infoXML.append("<url><![CDATA[").append(videoUrl).append("]]></url>");
		infoXML.append("</vi></vd></root>");

		resp.setContentType("text/xml; charset=UTF-8");
		resp.setCharacterEncoding("utf-8");
		resp.getWriter().print(infoXML);
	}

	private String getVideoURL(String vid){
		// 计算tot
		BigInteger tot = BigInteger.valueOf(0);
		BigInteger modder = new BigInteger("4294967296");
		for(int i=0; i<vid.length(); i++){
			int c = vid.charAt(i);
			tot = tot.multiply(BigInteger.valueOf(33)).add(BigInteger.valueOf(c));

			if(tot.compareTo(modder) >= 0){
				tot = tot.remainder(modder);
			}
		}
		// 计算fs
		BigInteger fs = tot.remainder(BigInteger.valueOf(10000 * 10000));
		String videoURL = new StringBuffer(QQ_VIDEO_URL).append(fs).append("/").append(vid).append(".flv").toString();
		return videoURL;
	}
}
